import React, { useImperativeHandle, useState } from 'react';
import { useRequest } from '@/hooks';
import { Modal, Form, Input, message, Alert } from 'antd';
import { backPrevious } from '@/pages/EntryManage/services';
import { replaceToWaitEntry } from '@/pages/EntryManage/utils';

/**
 * 退回弹窗
 */
const SendBackModal = React.forwardRef(
    ({ entryPersonnelCode, form, title = '审批退回', waringMessage, ...rest }, ref) => {
        const [visible, setVisible] = useState(false);
        const { getFieldDecorator } = form;

        const { run, loading } = useRequest(params => backPrevious(params), {
            manual: true
        });
        useImperativeHandle(ref, () => ({
            show: () => {
                setVisible(true);
            }
        }));

        return (
            <Modal
                title={title}
                visible={visible}
                confirmLoading={loading}
                onOk={() => {
                    form.validateFields(async (err, values) => {
                        if (!err) {
                            const params = {
                                entryPersonnelCode,
                                remark: values?.remark
                            };
                            const { msg, code } = await run(params);
                            if (code === 10000) {
                                message.success(msg);
                                setVisible(false);
                                replaceToWaitEntry();
                            } else {
                                message.error(msg);
                            }
                        }
                    });
                }}
                onCancel={() => {
                    setVisible(false);
                }}
                {...rest}
            >
                <Form labelCol={{ span: 5 }} wrapperCol={{ span: 16 }}>
                    {waringMessage && (
                        <Alert message={waringMessage} type="warning" showIcon style={{ margin: '-13px -12px 20px' }} />
                    )}
                    <Form.Item label="退回原因" help="2~100个字符">
                        {getFieldDecorator('remark', {
                            rules: [
                                { required: true, message: '2~100 个字符' },
                                {
                                    min: 2,
                                    max: 100,
                                    message: '请输入2~100个字符'
                                }
                            ]
                        })(<Input.TextArea placeholder="请输入退回原因" rows={4} />)}
                    </Form.Item>
                </Form>
            </Modal>
        );
    }
);

export default Form.create()(SendBackModal);
